import { h, markRaw } from 'vue'
import { toast as toastOriginal } from 'vue-sonner'
import type { ExternalToast, ToastProps } from './types'
import Toast from '@core/components/app-sonner/Toast.vue'

type Options = Omit<ToastProps, 'text'> & Pick<ExternalToast, 'duration' | 'onAutoClose' | 'onDismiss' | 'id' | 'important'>

function toastFunction(text: string, options?: Options) {
  const { description, action,position, ...rest } = options || {}
  return toastOriginal.custom(markRaw(h(Toast, {
    ...rest,
    progressBar: options?.progressBar ?? false,
    progressDuration: options?.duration ?? 5000,
    progressBarProps: {
      ...options?.progressBarProps,
      indeterminate: options?.loading,
    },
    description,
    action,
    text,
  })), {
    position: position || 'top-center',
    ...rest,
    unstyled: true,
  })
}

function createToastFunction(color: string, icon: string) {
  return function (text: string, options?: Options) {
    return toastFunction(text, {
      prependIcon: icon,
      cardProps: {
        color,
        ...options?.cardProps,
      },
      ...options,
    })
  }
}


function createNotification() {
  return function (text: string, description?: string) {
    return toastFunction(text, {
      prependIcon: 'tabler-info-circle',
      cardProps: {
        color:'info',
      },
      description: description,
      duration: 5000,
      progressBar: true,
      progressBarProps: {
        color: 'primary',
      },
    })
  }
}

export const toast = Object.assign(toastFunction, {
  success: createToastFunction('success', 'tabler-circle-check'),
  error: createToastFunction('error', 'tabler-ban'),
  warning: createToastFunction('warning', 'tabler-alert-square-filled'),
  info: createToastFunction('info', 'tabler-info-circle'),
  primary: createToastFunction('primary', 'mdi-bell'),
  secondary: createToastFunction('secondary', 'mdi-bell'),
  notification: createNotification(),
  dismiss(toastId?: number | string) {
    return toastOriginal.dismiss(toastId)
  },
  toastOriginal,
})

export const register = (app) => {
    app.config.globalProperties.$toast = toast;
    app.provide("$toast", toast);
}
